from fastapi import APIRouter, Depends, HTTPException
from basic.s3 import (
    S3,
    generate_random_string_in,
)

router = APIRouter(prefix="/s3", tags=["files"])


@router.get("/presigned_download")
async def presigned_download(object_key: str, bucket_key: str, service: S3 = Depends(S3)):
    try:
        url = service.presigned_download_url(bucket_key, object_key, expires_in=60)
        if not url:
            raise HTTPException(status_code=500, detail="生成预签名 URL 时出错")

        return {"url": url}
    except Exception as e:
        print(e)
        raise e


@router.get("/presigned_upload")
async def presigned_upload(bucket_key: str, service: S3 = Depends(S3)):
    try:
        object_key = generate_random_string_in(64)
        url = service.presigned_upload_url(bucket_key, object_key, expires_in=60)
        if not url:
            raise HTTPException(status_code=500, detail="生成预签名上传 URL 时出错")
        return {"url": url, "key": object_key}
    except Exception as e:
        print(e)
        raise e
